﻿@{
    ViewBag.Title = "图片上传";
}
<html>
<head>
    <title>HTML5 FileReader图片上传</title>
    <link href="css/smart-green.css" rel="stylesheet" />
    <link href="~/Css/jquery.Jcrop.min.css" rel="stylesheet" />
    <script src="~/Js/jquery.min.js"></script>
    <script src="~/Js/layer/layer.js"></script>
    <script src="~/Js/jquery.Jcrop.min.js"></script>
    <style>
        body ul li {
            list-style-type: none;
            padding: 5px;
        }

        #showbox ul {
            padding-left: 20px;
        }
    </style>
</head>
<body>
    <form method="post">
        <div class="smart-green">
            <h1>
                HTML5 FileReader图片上传
                <span>图片先加载到内存，裁剪后再保存到服务器，减少服务器资源.</span>
            </h1>
            <ul>
                <li>
                    <input type="file" name="imgupload" id="imgupload" onchange="showPreview(this)" />
                </li>
                <li>
                    <div id="div-imgupload">
                        <img src="~/Images/null.jpg" style="height:300px;" />
                    </div>
                </li>
                <li>
                    <input type="submit" value="保存" class="button-blue lef_8" onclick="return checkdata();" />
                    <input type="button" id="clearimg" name="clearimg" value="删除图片" class="button lef_8" onclick="deleteImg('imgupload');" />
                    <input type="button" id="cutimg" name="cutimg" value="裁剪" class="button lef_8" style="display:none;" onclick="showImg();" />
                </li>
                <li><span><img src="@ViewBag.Imgurl" /></span></li>
                <li><span style="color:red;">@ViewBag.msg</span></li>
            </ul>
            <div id="showbox" style="display:none;">
                <ul>
                    <li>
                        <div id="imgbox" style="text-align:center;">
                            @*<img id="target" src="" style="height:400px" />*@
                        </div>
                    </li>
                    <li>
                        <div class="coords">
                            <label>横坐标：<input type="text" size="4" id="x1" name="x1" class="txt10" /></label>
                            <label>纵坐标：<input type="text" size="4" id="y1" name="y1" class="txt10" /></label>
                            <label style="display:none">结束横坐标<input type="text" size="4" id="x2" name="x2" /></label>
                            <label style="display:none">结束纵坐标<input type="text" size="4" id="y2" name="y2" /></label>
                            <label>宽度：<input type="text" size="4" id="w" name="w" class="txt10" /></label>
                            <label>高度：<input type="text" size="4" id="h" name="h" class="txt10" /></label>
                        </div>
                    </li>
                    <li>
                        裁剪比例：&nbsp;&nbsp;
                        <label for="ratio_0">任意比例</label><input type="radio" id="ratio_0" name="proportion" value="0,0" checked="checked" />&nbsp;&nbsp;
                        <label for="ratio_1">1:1</label><input type="radio" id="ratio_1" name="proportion" value="1,1" />&nbsp;&nbsp;
                        <label for="ratio_2">4:3</label><input type="radio" id="ratio_2" name="proportion" value="4,3" />&nbsp;&nbsp;
                        <label for="ratio_3">16:9</label><input type="radio" id="ratio_3" name="proportion" value="16,9" />
                    </li>
                    <li>
                        <input type="button" value="确定" class="button" onclick="cutImg();" />
                    </li>

                </ul>
            </div>
        </div>
        <input type="hidden" id="imgvalue" name="imgvalue" />
    </form>
</body>

<script type="text/javascript">

    function checkdata() {
        var path = $.trim($('#imgvalue').val());
        if (!path) {
            layer.alert('请先上传图片！')
            return false;
        }
        else {
            return true;
        }
    }

    //弹出层
    function showImg() {
        var width = 800;// $('#imgupload-img').width() + 100;
        var height = 600;//k $('#imgupload-img').height() + 200;
        //页面层
        layer.open({
            type: 1,
            maxmin: true,
            //skin: 'layui-layer-rim', //加上边框
            area: [width + 'px', height + 'px'], //宽高
            content: $('#showbox')
        });
        jcrop(0,0);
    }

    //FileReader对象读取图片流
    function showPreview(source) {
        var file = source.files[0];
        var thisid = source.id;
        //限定上传文件的类型
        if (!/image\/\w+/.test(file.type)) {
            alert("请确保文件为图像类型");
            return false;
        }

        if (window.FileReader) {
            var fr = new FileReader();
            fr.onloadend = function (e) {
                //$('#imgupload-img').attr('src', e.target.result);
                //$('#target').attr('src', e.target.result);
                var obj = '<img id="' + thisid + '-img" src="' + e.target.result + '" />';
                $('#div-' + thisid).html(obj);//加载图片
                var obj1 = '<img id="target" src="' + e.target.result + '" />';
                $('#imgbox').html(obj1);//加载图片
                $('#cutimg').show();//显示裁剪按钮
                $('#imgvalue').val(e.target.result);//赋值给隐藏控件
            };
            fr.readAsDataURL(file);
        }
    }

    $(function () {       
        $('input[name="proportion"]:radio').click(function () {
            var arr = $(this).val().split(',');
            jcrop(arr[0], arr[1]);
        });
    });

    //删除图片
    function deleteImg(id) {
        $('#div-' + id).html('<img src="../Images/null.jpg" style="height:300px;" />');
        $('#imgbox').html('');
        $('#imgvalue').val('');
        $('#cutimg').hide();
    }

    //输出裁剪图片
    function cutImg() {
        //var x = $('#x1').val(); //裁剪左上角开始，横坐标
        //var y = $('#y1').val(); //裁剪左上角开始，纵坐标
        //var w = $('#w').val(); //裁剪宽度
        //var h = $('#h').val(); //裁剪高度
        //alert(x + "/" + y + "/" + w + "/" + h);

        var imgw = $('#target').width(); // 原图宽
        var imgh = $('#target').height(); // 原图高
        var cropw = $('#w').val(); // 剪切的宽
        var croph = $('#h').val(); // 剪切的高
        var poleft = 0 - $('#x1').val(); // canvas定位图片的左边位置
        var potop = 0 - $('#y1').val(); // canvas定位图片的上边位置

        //定义一个canvas对象
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        canvas.width = cropw;
        canvas.height = croph;

        var img = new Image();
        img.src = $('#target').attr('src');//填充base64图像

        img.onload = function () {
            this.width = imgw;
            this.height = imgh;
            // 这里调用canvas的drawImage方法，具体用法请百度
            ctx.drawImage(this, poleft, potop, this.width, this.height);
            var base64 = canvas.toDataURL('image/jpg', 1);  // 这里的“1”是指的是处理图片的清晰度（0-1）之间，当然越小图片越模糊，处理后的图片大小也就越小

            $('#imgupload-img').attr('src', base64);
            $('#imgvalue').val(base64);
            layer.closeAll();//关闭弹出层
        }
    }
</script>
<script type="text/javascript">
    // Create variables (in this scope) to hold the API and image size
    var jcrop_api,
		boundx,
		boundy,

		// Grab some information about the preview pane
		$preview = $('#preview-pane'),
		$pcnt = $('#preview-pane .preview-container'),
		$pimg = $('#preview-pane .preview-container img'),

		xsize = $pcnt.width() * 2,
		ysize = $pcnt.height() * 2;

    function jcrop(w, h) {
        $('#target').Jcrop({
            aspectRatio: w == 0 ? 0 : w / h, //选框宽高比。说明：width/height
            //aspectRatio: 0,
            onChange: showCoords,//当裁剪框变动时执行的函数
            onSelect: showCoords,//当选择完成时执行的函数
            onRelease: clearCoords,
            keySupport: false //注意：jcrop有一个bug,默认会出现一个radio控件，设置false隐藏
            //setSelect: [100, 100, 300, 300] //设定4个角的初始位置
        }, function () {
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            $preview.appendTo(jcrop_api.ui.holder);
        });

        $('.coords').on('change', 'input', function (e) {
            var x1 = $('#x1').val(),
				x2 = $('#x2').val(),
				y1 = $('#y1').val(),
				y2 = $('#y2').val();
            jcrop_api.setSelect([x1, y1, x2, y2]);
        });
    }

    function showCoords(c) {
        $('#x1').val(parseInt(c.x));
        $('#y1').val(parseInt(c.y));
        $('#x2').val(parseInt(c.x2));
        $('#y2').val(parseInt(c.y2));
        $('#w').val(parseInt(c.w));
        $('#h').val(parseInt(c.h));

        if (parseInt(c.w) > 0) {
            var rx = xsize / c.w;
            var ry = ysize / c.h;

            $pimg.css({
                width: Math.round(rx * boundx) + 'px',
                height: Math.round(ry * boundy) + 'px',
                marginLeft: '-' + Math.round(rx * c.x) + 'px',
                marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
        }
    }

    function clearCoords() {
        $('.coords input').val('');
    };
</script>
</html>